# config.py - 配置文件管理
import json
import os
import threading
import sys
# 确保系统使用UTF-8编码
if sys.version_info.major == 3:
    sys.stdout.reconfigure(encoding='utf-8')
CONFIG_PATH = "config.json"
# 全局系统状态变量
system_running = True
system_lock = threading.Lock()

def load_config():
    """加载配置文件"""
    if os.path.exists(CONFIG_PATH):
        try:
            with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return {"users": [], "next_id": 0}
    return {"users": [], "next_id": 0}

def save_config(config):
    """保存配置文件"""
    with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=4)

def get_user_names():
    """获取用户名称列表"""
    config = load_config()
    return config.get("users", [])

def add_user_name(user_name):
    """添加新用户名称"""
    config = load_config()
    if user_name not in config["users"]:
        user_id = config["next_id"]
        config["users"].append(user_name)
        config["next_id"] += 1
        save_config(config)
        return user_id
    return config["users"].index(user_name)  # 用户已存在，返回其索引

def remove_user_name(user_name):
    """移除用户名称"""
    config = load_config()
    if user_name in config["users"]:
        config["users"].remove(user_name)
        save_config(config)
        return True
    return False
def set_system_running(status):
    """设置系统运行状态"""
    global system_running
    with system_lock:
        system_running = status

def is_system_running():
    """检查系统是否正在运行"""
    global system_running
    with system_lock:
        return system_running